var userid
$.ajax({
    url:"/user/findByName",
    type:"POST",
    async:false,
    data: {
        username:$.cookie("username")
    },
    success:function (res){
        $("#realName").val(res.data.realname);
        $("#gender").val(res.data.gender)
        $("#phone").val(res.data.phone)
        $("#age").val(res.data.age)
        $("#email").val(res.data.email)
        $("#idCard").val(res.data.idCard)
        $("#bio").val(res.data.description)
        $("#userAvatar").attr("src", res.data.icon)
        userid = res.data.id
    }
})
$(".back-btn").on("click",function (res){
    window.location.href = "/iframeClient";
})
// 处理头像上传
function handleAvatarUpload(event) {
    const file = event.target.files[0];
    if (file) {
        // 验证文件类型和大小
        if (!validateFileType(file, ['image/jpeg', 'image/png', 'image/jpg'])) {
            alert('请上传JPEG或PNG格式的图片');
            return;
        }
        if (!validateFileSize(file, 2)) { // 2MB限制
            alert('图片大小不能超过2MB');
            return;
        }

        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('userAvatar').src = e.target.result;
        };
        reader.readAsDataURL(file);
    }
}

// 处理身份证照片上传
function handleIdCardUpload(event) {
    handleFileUpload(event, 'idCardPreview', ['image/jpeg', 'image/png', 'image/jpg'], 5); // 5MB限制
}

// 处理营业执照上传
function handleBusinessLicenseUpload(event) {
    handleFileUpload(event, 'businessLicensePreview', ['image/jpeg', 'image/png', 'image/jpg', 'application/pdf'], 10); // 10MB限制
}

// 处理其他材料上传
function handleOtherDocumentsUpload(event) {
    handleFileUpload(event, 'otherDocumentsPreview', ['image/jpeg', 'image/png', 'image/jpg', 'application/pdf'], 10); // 10MB限制
}

// 通用文件上传处理函数
function handleFileUpload(event, previewId, allowedTypes, maxSizeMB) {
    const files = event.target.files;
    const previewContainer = document.getElementById(previewId);

    for (let i = 0; i < files.length; i++) {
        const file = files[i];

        // 验证文件类型
        if (!validateFileType(file, allowedTypes)) {
            alert(`文件 "${file.name}" 格式不支持，请上传 ${allowedTypes.join(', ')} 格式的文件`);
            continue;
        }

        // 验证文件大小
        if (!validateFileSize(file, maxSizeMB)) {
            alert(`文件 "${file.name}" 大小超过 ${maxSizeMB}MB 限制`);
            continue;
        }

        const reader = new FileReader();

        reader.onload = function(e) {
            const previewItem = document.createElement('div');
            previewItem.className = 'document-preview-item';

            // 存储上传后的文件URL
            let uploadedFileUrl = '';

            // 如果是PDF文件
            if (file.type === 'application/pdf') {
                const pdfIcon = document.createElement('div');
                pdfIcon.className = 'pdf-preview';
                pdfIcon.innerHTML = `
                    <i class="bi bi-file-earmark-pdf" style="font-size: 48px; color: #dc3545;"></i>
                    <div class="uploading-text">上传中...</div>
                    <div style="font-size: 12px; margin-top: 5px;">${file.name}</div>
                `;
                previewItem.appendChild(pdfIcon);

                // 添加加载状态
                const loadingSpinner = document.createElement('div');
                loadingSpinner.className = 'upload-loading';
                loadingSpinner.innerHTML = '<i class="bi bi-arrow-repeat"></i>';
                previewItem.appendChild(loadingSpinner);

            } else {
                // 图片文件 - 先显示本地预览
                const img = document.createElement('img');
                img.src = e.target.result;
                img.alt = file.name;

                // 添加加载覆盖层
                const loadingOverlay = document.createElement('div');
                loadingOverlay.className = 'upload-loading-overlay';
                loadingOverlay.innerHTML = '<div class="uploading-text">上传中...</div>';

                previewItem.appendChild(img);
                previewItem.appendChild(loadingOverlay);
            }

            const removeBtn = document.createElement('button');
            removeBtn.className = 'document-remove-btn';
            removeBtn.innerHTML = '<i class="bi bi-x"></i>';
            removeBtn.onclick = function() {
                previewItem.remove();
                updateFileInput(event.target, file);
                // 可选：调用后端删除已上传的文件
                if (uploadedFileUrl) {
                    deleteUploadedFile(uploadedFileUrl);
                }
            };

            const fileName = document.createElement('div');
            fileName.className = 'file-name';
            fileName.textContent = file.name.length > 20 ? file.name.substring(0, 20) + '...' : file.name;
            fileName.style.fontSize = '12px';
            fileName.style.marginTop = '5px';
            fileName.style.textAlign = 'center';

            previewItem.appendChild(removeBtn);
            previewItem.appendChild(fileName);
            previewContainer.appendChild(previewItem);

            // 在这里添加文件上传到后端的代码
            const formData = new FormData();
            console.log("file是什么: ", file);
            formData.append("file", file);  // "file" 必须和后端参数名一致

            $.ajax({
                url: "/upload",  // 替换为你的Servlet URL
                type: "POST",
                data: formData,
                processData: false,      // 禁止jQuery处理数据（文件上传必须）
                contentType: false,      // 禁止设置Content-Type（浏览器自动生成multipart/form-data）
                cache: false,            // 禁用缓存
                success: function (response) {
                    // 上传成功后的处理
                    uploadedFileUrl = response.data; // 假设后端返回文件的访问URL
                    console.log("文件上传成功:", uploadedFileUrl);

                    // 移除加载状态
                    const loadingElement = previewItem.querySelector('.upload-loading-overlay, .upload-loading');
                    if (loadingElement) {
                        loadingElement.remove();
                    }

                    // 更新图片src为服务器返回的URL（如果是图片）
                    if (file.type.startsWith('image/')) {
                        const img = previewItem.querySelector('img');
                        if (img) {
                            img.src = uploadedFileUrl;
                        }
                    }

                    // 更新上传状态显示
                    const uploadingText = previewItem.querySelector('.uploading-text');
                    if (uploadingText) {
                        uploadingText.textContent = '上传成功';
                        uploadingText.style.color = '#28a745';
                    }

                    // 存储文件URL到预览项的数据属性中，便于后续使用
                    previewItem.setAttribute('data-file-url', uploadedFileUrl);

                },
                error: function(xhr, status, error) {
                    console.error("上传失败:", error);

                    // 更新上传状态显示
                    const uploadingText = previewItem.querySelector('.uploading-text');
                    if (uploadingText) {
                        uploadingText.textContent = '上传失败';
                        uploadingText.style.color = '#dc3545';
                    }

                    // 可选：添加重试按钮
                    const retryBtn = document.createElement('button');
                    retryBtn.className = 'retry-upload-btn';
                    retryBtn.innerHTML = '<i class="bi bi-arrow-clockwise"></i> 重试';
                    retryBtn.onclick = function() {
                        retryBtn.remove();
                        // 重新上传逻辑
                        uploadFileToServer(file, previewItem);
                    };
                    previewItem.appendChild(retryBtn);
                }
            });
        };

        reader.readAsDataURL(file);
    }
}
// 单独的文件上传函数，便于重试
function uploadFileToServer(file, previewItem) {
    const formData = new FormData();
    formData.append("file", file);

    // 显示加载状态
    const loadingOverlay = document.createElement('div');
    loadingOverlay.className = 'upload-loading-overlay';
    loadingOverlay.innerHTML = '<div class="uploading-text">上传中...</div>';
    previewItem.appendChild(loadingOverlay);

    $.ajax({
        url: "/upload",
        type: "POST",
        data: formData,
        processData: false,
        contentType: false,
        cache: false,
        success: function (response) {
            loadingOverlay.remove();
            const uploadedFileUrl = response.data;
            previewItem.setAttribute('data-file-url', uploadedFileUrl);

            // 更新状态显示
            const uploadingText = previewItem.querySelector('.uploading-text');
            if (uploadingText) {
                uploadingText.textContent = '上传成功';
                uploadingText.style.color = '#28a745';
            }
        },
        error: function(xhr, status, error) {
            loadingOverlay.remove();
            console.error("重试上传失败:", error);
        }
    });
}

// 删除已上传的文件（可选）
function deleteUploadedFile(fileUrl) {
    $.ajax({
        url: "/deleteUpload",
        type: "POST",
        data: { fileUrl: fileUrl },
        success: function(response) {
            console.log("文件删除成功:", fileUrl);
        },
        error: function(xhr, status, error) {
            console.error("文件删除失败:", error);
        }
    });
}

// 在表单提交时收集所有上传的文件URL
function collectUploadedFiles() {
    const uploadedFiles = {
        idCards: [],
        businessLicense: [],
        otherDocuments: []
    };

    // 收集身份证照片URL
    const idCardPreviews = document.getElementById('idCardPreview').querySelectorAll('.document-preview-item');
    idCardPreviews.forEach(item => {
        const fileUrl = item.getAttribute('data-file-url');
        if (fileUrl) uploadedFiles.idCards.push(fileUrl);
    });

    // 收集营业执照URL
    const businessLicensePreviews = document.getElementById('businessLicensePreview').querySelectorAll('.document-preview-item');
    businessLicensePreviews.forEach(item => {
        const fileUrl = item.getAttribute('data-file-url');
        if (fileUrl) uploadedFiles.businessLicense.push(fileUrl);
    });

    // 收集其他材料URL
    const otherDocumentsPreviews = document.getElementById('otherDocumentsPreview').querySelectorAll('.document-preview-item');
    otherDocumentsPreviews.forEach(item => {
        const fileUrl = item.getAttribute('data-file-url');
        if (fileUrl) uploadedFiles.otherDocuments.push(fileUrl);
    });

    return uploadedFiles;
}
// 文件类型验证
function validateFileType(file, allowedTypes) {
    return allowedTypes.includes(file.type);
}

// 文件大小验证 (MB)
function validateFileSize(file, maxSizeMB) {
    const maxSize = maxSizeMB * 1024 * 1024; // 转换为字节
    return file.size <= maxSize;
}

// 更新文件输入（移除文件时）
function updateFileInput(fileInput, removedFile) {
    // 创建新的FileList（由于FileList是只读的，需要重新创建input）
    const newFiles = Array.from(fileInput.files).filter(file => file !== removedFile);

    // 创建新的DataTransfer对象
    const dataTransfer = new DataTransfer();
    newFiles.forEach(file => dataTransfer.items.add(file));

    // 更新文件输入
    fileInput.files = dataTransfer.files;
}

// 身份证号码验证
function validateIdCard(idCard) {
    // 基本格式验证
    const idCardRegex = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[\dXx]$/;
    if (!idCardRegex.test(idCard)) {
        return {
            isValid: false,
            message: '身份证号码格式不正确'
        };
    }

    // 校验码验证
    if (!validateIdCardCheckCode(idCard)) {
        return {
            isValid: false,
            message: '身份证号码校验码错误'
        };
    }

    return {
        isValid: true,
        message: '身份证号码格式正确'
    };
}

// 身份证校验码验证
function validateIdCardCheckCode(idCard) {
    if (idCard.length !== 18) return false;

    const factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
    const parity = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
    let sum = 0;

    for (let i = 0; i < 17; i++) {
        sum += parseInt(idCard.charAt(i)) * factor[i];
    }

    const mod = sum % 11;
    return parity[mod] === idCard.charAt(17).toUpperCase();
}

// 手机号验证
function validatePhone(phone) {
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(phone)) {
        return {
            isValid: false,
            message: '手机号码格式不正确'
        };
    }

    return {
        isValid: true,
        message: '手机号码格式正确'
    };
}

// 邮箱验证
function validateEmail(email) {
    const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    if (!emailRegex.test(email)) {
        return {
            isValid: false,
            message: '邮箱格式不正确'
        };
    }

    return {
        isValid: true,
        message: '邮箱格式正确'
    };
}

// 实时验证函数
function setupRealTimeValidation() {
    // 身份证实时验证
    const idCardInput = document.getElementById('idCard');
    if (idCardInput) {
        idCardInput.addEventListener('blur', function() {
            const value = this.value.trim();
            if (value) {
                const result = validateIdCard(value);
                showValidationMessage(this, result);
            }
        });
    }

    // 手机号实时验证
    const phoneInput = document.getElementById('phone');
    if (phoneInput) {
        phoneInput.addEventListener('blur', function() {
            const value = this.value.trim();
            if (value) {
                const result = validatePhone(value);
                showValidationMessage(this, result);
            }
        });
    }

    // 邮箱实时验证
    const emailInput = document.getElementById('email');
    if (emailInput) {
        emailInput.addEventListener('blur', function() {
            const value = this.value.trim();
            if (value) {
                const result = validateEmail(value);
                showValidationMessage(this, result);
            }
        });
    }
}

// 显示验证消息
function showValidationMessage(inputElement, validationResult) {
    // 移除现有的验证消息
    const existingMessage = inputElement.parentNode.querySelector('.field-validation-message');
    if (existingMessage) {
        existingMessage.remove();
    }

    // 添加新的验证消息
    const messageElement = document.createElement('div');
    messageElement.className = `field-validation-message ${validationResult.isValid ? 'validation-success' : 'validation-error'}`;
    messageElement.textContent = validationResult.message;
    messageElement.style.fontSize = '12px';
    messageElement.style.marginTop = '5px';

    // 更新输入框样式
    inputElement.style.borderColor = validationResult.isValid ? '#28a745' : '#dc3545';

    inputElement.parentNode.appendChild(messageElement);
}

// 表单提交处理
document.getElementById('ownerApplicationForm').addEventListener('submit', function(event) {
    event.preventDefault();

    // 重置所有验证样式
    resetValidationStyles();

    // 表单字段验证
    const requiredFields = document.querySelectorAll('[required]');
    let isValid = true;
    let errorMessages = [];

    // 验证必填字段
    requiredFields.forEach(field => {
        if (!field.value.trim()) {
            isValid = false;
            field.style.borderColor = '#dc3545';
            errorMessages.push(`${field.previousElementSibling?.textContent || '该字段'}不能为空`);
        }
    });

    // 验证身份证号码
    const idCard = document.getElementById('idCard').value.trim();
    if (idCard) {
        const idCardResult = validateIdCard(idCard);
        if (!idCardResult.isValid) {
            isValid = false;
            document.getElementById('idCard').style.borderColor = '#dc3545';
            errorMessages.push(idCardResult.message);
        }
    }

    // 验证手机号
    const phone = document.getElementById('phone').value.trim();
    if (phone) {
        const phoneResult = validatePhone(phone);
        if (!phoneResult.isValid) {
            isValid = false;
            document.getElementById('phone').style.borderColor = '#dc3545';
            errorMessages.push(phoneResult.message);
        }
    }

    // 验证邮箱
    const email = document.getElementById('email').value.trim();
    if (email) {
        const emailResult = validateEmail(email);
        if (!emailResult.isValid) {
            isValid = false;
            document.getElementById('email').style.borderColor = '#dc3545';
            errorMessages.push(emailResult.message);
        }
    }

    // 检查身份证照片是否上传
    const idCardPreview = document.getElementById('idCardPreview');
    if (idCardPreview.children.length === 0) {
        isValid = false;
        errorMessages.push('请上传身份证照片');
    }

    // 检查营业执照是否上传
    const businessLicensePreview = document.getElementById('businessLicensePreview');
    if (businessLicensePreview.children.length === 0) {
        isValid = false;
        errorMessages.push('请上传营业执照');
    }

    // 验证年龄范围
    const age = parseInt(document.getElementById('age').value);
    if (age < 18 || age > 100) {
        isValid = false;
        document.getElementById('age').style.borderColor = '#dc3545';
        errorMessages.push('年龄必须在18-100岁之间');
    }

    if (isValid) {
        // 收集表单数据
        const formData = collectFormData();

        // 在实际应用中，这里应该发送AJAX请求到后端
        console.log('表单数据:', formData);

        // 模拟提交成功
        document.getElementById('successModal').style.display = 'flex';
    } else {
        // 显示所有错误信息
        showErrorMessages(errorMessages);
    }
});

// 收集表单数据
function collectFormData() {
    let idCardImg = []
    for(var i = 0; i < $("#idCardPreview .document-preview-item").length; i++){
        // 使用 jQuery 的 data() 方法或 attr() 方法
        let fileUrl = $("#idCardPreview .document-preview-item").eq(i).data('file-url');
        // 或者使用：let fileUrl = $("#idCardPreview .document-preview-item").eq(i).attr('data-file-url');
        if(fileUrl) {
            idCardImg.push(fileUrl);
        }
    }

    let businessLicense = []
    for(var i = 0; i < $("#businessLicensePreview .document-preview-item").length; i++){
        let fileUrl = $("#businessLicensePreview .document-preview-item").eq(i).data('file-url');
        if(fileUrl) {
            businessLicense.push(fileUrl);
        }
    }

    let verifyImg = []
    for(var i = 0; i < $("#otherDocumentsPreview .document-preview-item").length; i++){
        let fileUrl = $("#otherDocumentsPreview .document-preview-item").eq(i).data('file-url');
        if(fileUrl) {
            verifyImg.push(fileUrl);
        }
    }

    console.log('身份证图片:', idCardImg);
    console.log('营业执照:', businessLicense);
    console.log('其他材料:', verifyImg);
    $.ajax({
        url:"userAduit/add",
        type:"POST",
        data:{
            userId:userid,
            aduitReason:$("#applyReason").val(),
            aduitExperience:$("#experience").val(),
            businessLicense:JSON.stringify(businessLicense),
            idCardImg:JSON.stringify(idCardImg),
            verifyImg:JSON.stringify(verifyImg),
        },
        success:function (data) {
            if(data.code==200){}
        }
    })
}

// 重置验证样式
function resetValidationStyles() {
    const inputs = document.querySelectorAll('input, textarea, select');
    inputs.forEach(input => {
        input.style.borderColor = '#ced4da';
    });

    // 移除所有验证消息
    const validationMessages = document.querySelectorAll('.field-validation-message');
    validationMessages.forEach(message => message.remove());
}

// 显示错误消息
function showErrorMessages(messages) {
    const errorContainer = document.createElement('div');
    errorContainer.className = 'error-container';
    errorContainer.style.cssText = `
    background-color: #f8d7da;
    color: #721c24;
    padding: 15px;
    border-radius: 4px;
    margin-bottom: 20px;
    border: 1px solid #f5c6cb;
  `;

    const errorTitle = document.createElement('div');
    errorTitle.textContent = '请修正以下错误：';
    errorTitle.style.fontWeight = 'bold';
    errorTitle.style.marginBottom = '10px';

    const errorList = document.createElement('ul');
    errorList.style.margin = '0';
    errorList.style.paddingLeft = '20px';

    messages.forEach(message => {
        const listItem = document.createElement('li');
        listItem.textContent = message;
        errorList.appendChild(listItem);
    });

    errorContainer.appendChild(errorTitle);
    errorContainer.appendChild(errorList);

    // 插入到表单顶部
    const form = document.getElementById('ownerApplicationForm');
    form.insertBefore(errorContainer, form.firstChild);

    // 5秒后自动移除错误消息
    setTimeout(() => {
        if (errorContainer.parentNode) {
            errorContainer.parentNode.removeChild(errorContainer);
        }
    }, 5000);
}

// 关闭成功模态框
function closeSuccessModal() {
    document.getElementById('successModal').style.display = 'none';
    // 在实际应用中，这里可以重定向到其他页面
    window.location.href = '/homePageClient';
}

// 页面加载完成后设置实时验证
document.addEventListener('DOMContentLoaded', function() {
    setupRealTimeValidation();
});